<template>
    <div class="min-h-screen bg-gradient-to-r  flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-5xl overflow-hidden">
        <nav class="bg-blue-500 p-4">
          <ul class="flex space-x-4 text-white">
            <li>
              <a href="#" @click.prevent="setActiveTab('today')" :class="{ 'font-bold': activeTab === 'today' }">今日知识点</a>
            </li>
            <li>
              <a href="#" @click.prevent="setActiveTab('all')" :class="{ 'font-bold': activeTab === 'all' }">全部知识点</a>
            </li>
          </ul>
        </nav>
       
        <!-- 今日知识点和全部知识点 -->
        <div class="p-6">
          <!-- 今日知识点 -->
          <div v-if="activeTab === 'today'">
            <!-- 数据加载中动画 -->
            <div v-if="isLoading" class="flex justify-center items-center py-20">
              <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
              <span class="ml-3 text-lg text-blue-500">正在加载知识点...</span>
            </div>
            
            <!-- 缩略图加载状态 -->
            <div v-else-if="isThumbnailLoading && todayKnowledgePoints.length > 0" class="flex flex-col justify-center items-center py-10">
              <div class="animate-pulse text-3xl mb-2">🖼️</div>
              <div class="text-lg font-bold text-blue-600 mb-2">正在准备缩略图</div>
              <p class="text-gray-500">为提升浏览体验，我们正在为您准备知识点缩略图...</p>
              <div class="mt-2 w-64 h-2 bg-gray-200 rounded-full overflow-hidden">
                <div class="h-full bg-blue-500 animate-pulse"></div>
              </div>
            </div>
            
            <!-- 生成中提示 -->
            <div v-else-if="todayKnowledgePoints.length === 0 && isGeneratingCards" class="flex flex-col justify-center items-center py-20">
              <div class="animate-bounce text-5xl mb-4">✨</div>
              <div class="text-xl font-bold text-blue-600 mb-2">正在生成知识卡片</div>
              <p class="text-gray-500">AI正在分析您的学习内容，很快就会为您生成知识卡片...</p>
              <div class="mt-4 w-64 h-2 bg-gray-200 rounded-full overflow-hidden">
                <div class="h-full bg-blue-500 animate-pulse"></div>
              </div>
            </div>
            
            <!-- 无数据提示 -->
            <div v-else-if="todayKnowledgePoints.length === 0" class="flex flex-col justify-center items-center py-20">
              <div class="text-5xl mb-4">📚</div>
              <div class="text-xl font-bold text-gray-600 mb-2">暂无今日知识点</div>
              <p class="text-gray-500">继续学习更多内容，系统将自动为您生成知识卡片</p>
            </div>
            
            <div v-else class="mb-4 flex space-x-2">
              <select
                v-if="activeTab === 'all'"
                v-model="selectedMaterial"
                class="px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                @change="filterKnowledgePoints"
              >
                <option value="">所有材料</option>
                <option v-for="material in materials" :key="material" :value="material.id">
                  {{ material.title }}
                </option>
              </select>
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索知识点..."
                class="flex-grow px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                @input="searchKnowledgePoints"
              />
              <select
                v-model="itemsPerPage"
                class="px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                @change="updatePagination"
              >
                <option :value="1">1条/页</option>
                <option :value="3">3条/页</option>
                <option :value="5">5条/页</option>
                <option :value="10">10条/页</option>
              </select>
            </div>
            
            <!--显示列表信息 (仅在数据存在且非生成中状态时显示)-->            
            <div v-if="todayKnowledgePoints.length > 0 && !isThumbnailLoading">
              <div v-for="point in paginatedTodayKnowledgePoints" :key="point.id" 
                class="bg-white rounded-lg shadow-md p-6 mb-4 cursor-pointer transition-all duration-300 transform hover:scale-105"
                :class="{'animate-fadeIn': point.isNew}"
                @click="openKnowledgeCard(point)">
                <div class="flex flex-col md:flex-row gap-4">
                  <div class="flex-grow">
                    <h2 class="text-2xl font-bold mb-4">{{ point.title }}</h2>
                    <p class="text-gray-700 mb-4">{{ point.summary || point.content.substring(0, 150) + '...' }}</p>
                    <p class="text-sm text-gray-500">来源:{{ point.material_title }}: {{ point.page_number }} 页</p>
                  </div>
                  <div class="w-32 h-32 flex-shrink-0 overflow-hidden rounded border border-gray-200 shadow-sm">
                    <!-- 所有缩略图都已预加载完成，直接显示 -->
                    <img :src="point.thumbnail" alt="内容预览" class="w-full h-full object-cover" />
                  </div>
                </div>
              </div>
            </div>
  

            <div class="flex justify-between items-center mt-4">
              <button
                @click="prevPage"
                class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition duration-300"
                :disabled="currentPage === 1"
              >
                上一页
              </button>
              <span class="text-gray-600">第 {{ currentPage }} 页，共 {{ totalTodayPages }} 页</span>
              <button
                @click="nextPage"
                class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition duration-300"
                :disabled="currentPage === totalTodayPages"
              >
                下一页
              </button>
            </div>
          </div>
  
          <!-- 全部知识点 -->
          <div v-if="activeTab === 'all'">
            <!-- 数据加载中动画 -->
            <div v-if="isLoading" class="flex justify-center items-center py-20">
              <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
              <span class="ml-3 text-lg text-blue-500">正在加载知识点...</span>
            </div>
            
            <!-- 缩略图加载状态 -->
            <div v-else-if="isThumbnailLoading && allKnowledgePoints.length > 0" class="flex flex-col justify-center items-center py-10">
              <div class="animate-pulse text-3xl mb-2">🖼️</div>
              <div class="text-lg font-bold text-blue-600 mb-2">正在准备缩略图</div>
              <p class="text-gray-500">为提升浏览体验，我们正在为您准备知识点缩略图...</p>
              <div class="mt-2 w-64 h-2 bg-gray-200 rounded-full overflow-hidden">
                <div class="h-full bg-blue-500 animate-pulse"></div>
              </div>
            </div>
            
            <!-- 生成中提示 -->
            <div v-else-if="allKnowledgePoints.length === 0 && isGeneratingCards" class="flex flex-col justify-center items-center py-20">
              <div class="animate-bounce text-5xl mb-4">✨</div>
              <div class="text-xl font-bold text-blue-600 mb-2">正在生成知识卡片</div>
              <p class="text-gray-500">AI正在分析您的学习内容，很快就会为您生成知识卡片...</p>
              <div class="mt-4 w-64 h-2 bg-gray-200 rounded-full overflow-hidden">
                <div class="h-full bg-blue-500 animate-pulse"></div>
              </div>
            </div>
            
            <!-- 无数据提示 -->
            <div v-else-if="allKnowledgePoints.length === 0" class="flex flex-col justify-center items-center py-20">
              <div class="text-5xl mb-4">📚</div>
              <div class="text-xl font-bold text-gray-600 mb-2">暂无知识点</div>
              <p class="text-gray-500">继续学习更多内容，系统将自动为您生成知识卡片</p>
            </div>
            
            <div v-else class="mb-4 flex space-x-2">
              <select
                v-if="activeTab === 'all'"
                v-model="selectedMaterial"
                class="px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                @change="filterKnowledgePoints"
              >
                <option value="">所有材料</option>
                <option v-for="material in materials" :key="material" :value="material.id">
                  {{ material.title }}
                </option>
              </select>
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索知识点..."
                class="flex-grow px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                @input="searchKnowledgePoints"
              />
              <select
                v-model="itemsPerPage"
                class="px-4 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
                @change="updatePagination"
              >
                <option :value="1">1条/页</option>
                <option :value="3">3条/页</option>
                <option :value="5">5条/页</option>
                <option :value="10">10条/页</option>
              </select>
            </div>
  
            <!--显示列表信息 (仅在数据存在且非生成中状态时显示)-->
            <div v-if="allKnowledgePoints.length > 0 && !isThumbnailLoading">
              <div v-for="point in paginatedAllKnowledgePoints" :key="point.id" 
                class="bg-white rounded-lg shadow-md p-6 mb-4 cursor-pointer transition-all duration-300 transform hover:scale-105"
                :class="{'animate-fadeIn': point.isNew}"
                @click="openKnowledgeCard(point)">
                <div class="flex flex-col md:flex-row gap-4">
                  <div class="flex-grow">
                    <h2 class="text-2xl font-bold mb-4">{{ point.title }}</h2>
                    <p class="text-gray-700 mb-4">{{ point.summary || point.content.substring(0, 150) + '...' }}</p>
                    <p class="text-sm text-gray-500">来源:{{ point.material_title }} : {{ point.page_number }} 页</p>
                  </div>
                  <div class="w-32 h-32 flex-shrink-0 overflow-hidden rounded border border-gray-200 shadow-sm">
                    <!-- 所有缩略图完成加载后显示 -->
                    <img :src="point.thumbnail" alt="内容预览" class="w-full h-full object-cover" />
                  </div>
                </div>
              </div>
            </div>
  
            <div class="flex justify-between items-center mt-4">
              <button
                @click="prevPage"
                class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition duration-300"
                :disabled="currentPage === 1"
              >
                上一页
              </button>
              <span class="text-gray-600">第 {{ currentPage }} 页，共 {{ totalAllPages }} 页</span>
              <button
                @click="nextPage"
                class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition duration-300"
                :disabled="currentPage === totalAllPages"
              >
                下一页
              </button>
            </div>
          </div>

        </div>
      </div>
    </div>

    <!-- 知识卡片弹框 -->
    <div v-if="showKnowledgeCard">
      <knowledgeCards 
        :htmlContent="selectedKnowledgePoint.content" 
        :initialX="null" 
        :initialY="null"
        class="z-50"
        @close="closeKnowledgeCard"
      />
      <div class="fixed z-40 inset-0 overflow-y-auto" @click.self="closeKnowledgeCard">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
          <div @click.self="closeKnowledgeCard" class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-40"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 全局消息组件 -->
    <showMessage ref="showMessageRef" />
  </template>
  
  <script setup>
  import { ref, computed, onMounted, watch, nextTick } from 'vue'
import axiosClient from '@/utils/axios'
import showMessage from '@/components/share/showMessage.vue'
import knowledgeCards from '@/components/section/knowledgeCards.vue'
import html2canvas from 'html2canvas'
import { useGeneralStore } from '@/stores/general'
import { useAuthStore } from '@/stores/auth'

// 初始化generalStore
const generalStore = useGeneralStore()
const authStore = useAuthStore();
  
  // 定义Tab类型
  const activeTab = ref('today')
  const searchQuery = ref('')
  const selectedMaterial = ref('')
  const itemsPerPage = ref(3)
  const currentPage = ref(1)
  const showAnswer = ref(false)
  const selectedAnswer = ref(null)
  const canGoBack = ref(false)
  const currentQuestionIndex = ref(0)
  const showKnowledgeCard = ref(false)
  const selectedKnowledgePoint = ref({
    id: '',
    title: '',
    content: '',
    summary: '',
    user_input: '',
    material_title: '',
    page_number: '',
    chapter: '',
  })
  const showMessageRef = ref(null)
  const isEditing = ref(false)
  const editingInput = ref('')
  const inputRef = ref(null)
  
  const materials = ref([])
  
  const todayKnowledgePoints = ref([])
  const allKnowledgePoints = ref([])
  
  
  const filteredTodayKnowledgePoints = computed(() => {
    return todayKnowledgePoints.value.filter(point =>
      point.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      point.content.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  })
  
  const filteredAllKnowledgePoints = computed(() => {
    return allKnowledgePoints.value.filter(point =>
      (!selectedMaterial.value || point.material_id === selectedMaterial.value) && 
      (point.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
       point.content.toLowerCase().includes(searchQuery.value.toLowerCase()))
    )

  })
  
  const totalTodayPages = computed(() => Math.ceil(filteredTodayKnowledgePoints.value.length / itemsPerPage.value))
  const totalAllPages = computed(() => Math.ceil(filteredAllKnowledgePoints.value.length / itemsPerPage.value))
  
  const paginatedTodayKnowledgePoints = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage.value
    const end = start + itemsPerPage.value
    return filteredTodayKnowledgePoints.value.slice(start, end)
  })
  
  const paginatedAllKnowledgePoints = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage.value
    const end = start + itemsPerPage.value
    return filteredAllKnowledgePoints.value.slice(start, end)  
  })
  
  
  function setActiveTab(tab) {
    activeTab.value = tab
    currentPage.value = 1
    searchQuery.value = ''
    selectedMaterial.value = ''
    resetQuestion()
  }
  
  function searchKnowledgePoints() {
    currentPage.value = 1
  }
  
  function filterKnowledgePoints() {
    currentPage.value = 1
    searchKnowledgePoints()
  }
  
  function updatePagination() {
    currentPage.value = 1
  }
  
  function prevPage() {
    if (currentPage.value > 1) {
      currentPage.value--
    }
  }
  
  function nextPage() {
    if (currentPage.value < totalTodayPages.value || currentPage.value < totalAllPages.value) {
      currentPage.value++
    }
  }
  
  
  function resetQuestion() {
    showAnswer.value = false
    selectedAnswer.value = null
    canGoBack.value = currentQuestionIndex.value > 0
  }
  
  function openKnowledgeCard(point) {
    selectedKnowledgePoint.value = point
    showKnowledgeCard.value = true
  }
  
  function closeKnowledgeCard() {
    showKnowledgeCard.value = false
  }
  
  // 生成内容缩略图
  async function generateThumbnail(point) {
    if (point.thumbnail) return;
    
    try {
      // 创建一个离屏div来渲染HTML内容
      const container = document.createElement('div');
      container.style.position = 'fixed';
      container.style.left = '-9999px';
      container.style.top = '0';
      container.style.width = '600px';
      container.style.backgroundColor = '#ffffff';
      container.style.padding = '20px';
      container.style.zIndex = '-1000';
      container.style.overflow = 'hidden';
      
      // 添加样式到内容
      const contentDiv = document.createElement('div');
      contentDiv.style.fontFamily = 'Arial, sans-serif';
      contentDiv.style.color = '#333';
      contentDiv.style.fontSize = '14px';
      contentDiv.style.lineHeight = '1.5';
      contentDiv.innerHTML = point.content;
      
      container.appendChild(contentDiv);
      document.body.appendChild(container);
      
      // 等待内容加载和渲染
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 使用html2canvas捕获内容
      const canvas = await html2canvas(container, {
        backgroundColor: '#ffffff',
        scale: 0.5,
        logging: false,
        useCORS: true,
        allowTaint: true,
        removeContainer: false
      });
      
      point.thumbnail = canvas.toDataURL('image/jpeg', 0.8);
      
      // 移除临时容器
      document.body.removeChild(container);
    } catch (e) {
      console.error('生成缩略图失败:', e);
      
      // 设置一个默认缩略图而不是显示错误
      point.thumbnail = createDefaultThumbnail(point.title);
    }
  }

  // 创建默认的文本缩略图
  function createDefaultThumbnail(title) {
    // 创建canvas
    const canvas = document.createElement('canvas');
    canvas.width = 300;
    canvas.height = 200;
    const ctx = canvas.getContext('2d');
    
    // 绘制背景
    ctx.fillStyle = '#f3f4f6';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制文本背景
    ctx.fillStyle = '#e5e7eb';
    ctx.fillRect(20, 60, canvas.width - 40, 80);
    
    // 绘制文本
    ctx.font = 'bold 16px Arial';
    ctx.fillStyle = '#374151';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // 截取标题长度并在中间显示
    let displayTitle = title;
    if (title.length > 20) {
      displayTitle = title.substring(0, 18) + '...';
    }
    ctx.fillText(displayTitle, canvas.width / 2, canvas.height / 2);
    
    return canvas.toDataURL('image/jpeg', 0.8);
  }

  // 缩略图加载状态控制变量
  const isThumbnailLoading = ref(false);

  // 处理显示内容缩略图 - 优化版本（批量处理所有缩略图）
  async function processKnowledgePoints(points) {
    // 筛选需要生成缩略图的知识点
    const pointsNeedingThumbnails = points.filter(point => !point.thumbnail && point.content);
    
    // 如果没有需要处理的缩略图，直接返回
    if (pointsNeedingThumbnails.length === 0) return;
    
    // 设置缩略图加载状态为true
    isThumbnailLoading.value = true;
    
    try {
      // 使用Promise.all并行处理所有缩略图
      // 这样可以一次性处理所有缩略图，而不是串行处理
      await Promise.all(
        pointsNeedingThumbnails.map(point => generateThumbnail(point))
      );
    } catch (error) {
      console.error('生成缩略图时出错:', error);
      // 错误处理：为未成功生成缩略图的知识点设置默认缩略图
      pointsNeedingThumbnails.forEach(point => {
        if (!point.thumbnail) {
          point.thumbnail = createDefaultThumbnail(point.title);
        }
      });
    } finally {
      // 无论成功与否，都将缩略图加载状态设为false
      isThumbnailLoading.value = false;
    }
  }

  // 生成知识卡片 (使用SSE方式)  
  async function generateKnowledgeCards() {
    try {
      // 设置生成中状态
      isGeneratingCards.value = true
      showMessageRef.value.showMessage('正在生成知识卡片...', 'info')
      
      // 从generalStore获取当前的material_id
      const materialId = generalStore.getMaterialId()
      
      // 关闭之前可能存在的EventSource连接
      let eventSource = null
      let generatedCount = 0
      
      // 创建SSE连接URL
      const url = new URL(`${axiosClient.defaults.baseURL}/card/generate`)
      
      // 创建一个Promise, 在所有卡片生成完成或发生错误时resolve
      await new Promise((resolve, reject) => {
        // 创建EventSource实例
        const headers = {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authStore.accessToken}`
        }
        
        const payload = JSON.stringify({
          material_id: materialId
        })
        
        // 由于EventSource不支持POST和自定义请求头，我们先创建一个POST请求来启动SSE流
        fetch(`${axiosClient.defaults.baseURL}/card/generate`, {
          method: 'POST',
          headers: headers,
          body: payload
        }).then(response => {
          if (!response.ok) {
            throw new Error(`服务器响应错误: ${response.status}`)
          }
          
          // 使用Response对象作为事件源
          const reader = response.body.getReader()
          const decoder = new TextDecoder()
          
          // 处理SSE消息
          const processSSE = async () => {
            try {
              while (true) {
                const { done, value } = await reader.read()
                
                if (done) break
                
                // 解码数据块
                const chunk = decoder.decode(value, { stream: true })
                
                // SSE格式: 每个事件由多行组成，空行分隔事件
                const events = chunk.split('\n\n').filter(e => e.trim())
                
                for (const eventText of events) {
                  const eventLines = eventText.split('\n')
                  let eventType = 'message'
                  let eventData = ''
                  let eventId = ''
                  
                  // 解析SSE事件
                  for (const line of eventLines) {
                    if (line.startsWith('event:')) {
                      eventType = line.substring(6).trim()
                    } else if (line.startsWith('data:')) {
                      eventData = line.substring(5).trim()
                    } else if (line.startsWith('id:')) {
                      eventId = line.substring(3).trim()
                    }
                  }
                  
                  // 处理不同类型的事件
                  if (eventType === 'connected') {
                    console.log('SSE连接已建立')
                    showMessageRef.value.showMessage('与服务器连接已建立，开始生成知识卡片...', 'info')
                  } 
                  else if (eventType === 'card' && eventData) {
                    try {
                      // 解析卡片数据
                      const event = JSON.parse(eventData)
                      
                      if (event.type === 'card' && event.data) {
                        const card = event.data
                        
                        // 检查是否是有效的卡片
                        if (card.id && card.title && card.html_content) {
                          // 转换数据格式
                          const formattedCard = {
                            id: card.id,
                            title: card.title,
                            content: card.html_content,
                            summary: card.summary,
                            material_title: card.material_title,
                            page_number: card.page_number,
                            created_at: card.created_at,
                            updated_at: card.updated_at,
                            isNew: true // 标记为新卡片，用于动画
                          }
                          
                          // 添加到今日知识点
                          todayKnowledgePoints.value.unshift(formattedCard)
                          // 添加到全部知识点
                          allKnowledgePoints.value.unshift(formattedCard)
                          
                          // 生成缩略图
                          await generateThumbnail(formattedCard)
                          
                          // 1.5秒后移除新卡片标记
                          setTimeout(() => {
                            formattedCard.isNew = false
                          }, 1500)
                          
                          generatedCount++
                          showMessageRef.value.showMessage(`已生成 ${generatedCount} 张知识卡片，继续生成中...`, 'info')
                        }
                      }
                    } catch (err) {
                      console.error('解析知识卡片数据失败:', err, eventData)
                    }
                  } 
                  else if (eventType === 'error') {
                    try {
                      const errorEvent = JSON.parse(eventData)
                      console.error('生成知识卡片时出错:', errorEvent.data?.error || '未知错误')
                      showMessageRef.value.showMessage(`生成知识卡片时出错: ${errorEvent.data?.error || '未知错误'}`, 'error')
                    } catch (err) {
                      console.error('解析错误消息失败:', err, eventData)
                    }
                  } 
                  else if (eventType === 'complete') {
                    try {
                      const completeEvent = JSON.parse(eventData)
                      console.log('知识卡片生成完成:', completeEvent)
                      
                      // 生成完毕
                      if (generatedCount > 0) {
                        showMessageRef.value.showMessage(`成功生成 ${generatedCount} 张知识卡片`, 'success')
                      } else {
                        showMessageRef.value.showMessage('没有新的知识卡片需要生成', 'info')
                      }
                      
                      // 完成Promise
                      resolve()
                    } catch (err) {
                      console.error('解析完成消息失败:', err, eventData)
                      resolve() // 即使解析失败，也完成Promise
                    }
                  }
                }
              }
              resolve() // 如果循环正常结束，完成Promise
            } catch (err) {
              console.error('处理SSE消息时发生错误:', err)
              reject(err)
            }
          }
          
          // 开始处理SSE流
          processSSE()
        }).catch(error => {
          console.error('创建SSE连接失败:', error)
          reject(error)
        })
      })
    } catch (error) {
      console.error('生成知识卡片失败:', error)
      showMessageRef.value.showMessage(`生成知识卡片失败: ${error.message}`, 'error')
    } finally {
      isGeneratingCards.value = false
    }
  }

  const isLoading = ref(false)
  const isGeneratingCards = ref(false)

  async function fetchKnowledgePoints() {
    try {
      isLoading.value = true
      let todayData = []
      let allData = []
      
      try {
        const todayResponse = await axiosClient.get('/card/today')
        todayData = todayResponse.data

        // 如果数据为空，显示生成中状态
        if (todayData.length === 0) {
          isGeneratingCards.value = true
        }
      } catch (error) {
        console.error('获取今日知识点失败:', error)
        showMessageRef.value.showMessage('获取今日知识点失败', 'error')
      }
      
      try {
        const allResponse = await axiosClient.get('/card')
        allData = allResponse.data

        // 如果数据为空，显示生成中状态
        if (allData.length === 0) {
          isGeneratingCards.value = true
        }
      } catch (error) {
        console.error('获取全部知识点失败:', error)
        showMessageRef.value.showMessage('获取全部知识点失败', 'error')
      }
      
      // 将获取到的数据转换为前端需要的格式，但还不立即赋值给响应式变量
      // 这样可以避免在预处理缩略图过程中触发多次渲染
      const processedTodayData = todayData.map(card => ({
        id: card.id,
        title: card.title,
        content: card.html_content,
        summary: card.summary,
        material_title: card.material_title,
        page_number: card.page_number,
        created_at: card.created_at,
        updated_at: card.updated_at,
        isNew: false,
        thumbnail: null // 初始化缩略图属性
      })).sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
      
      const processedAllData = allData.map(card => ({
        id: card.id,
        title: card.title,
        content: card.html_content,
        summary: card.summary,
        material_title: card.material_title,
        page_number: card.page_number,
        created_at: card.created_at,
        updated_at: card.updated_at,
        thumbnail: null, // 初始化缩略图属性
        isNew: false 
      })).sort((a, b) => new Date(b.created_at) - new Date(a.created_at))

      // 今日知识点缩略图预加载
      if (processedTodayData.length > 0) {
        // 设置缩略图加载状态
        isThumbnailLoading.value = true;
        // 先预加载今日知识点的缩略图
        await processKnowledgePoints(processedTodayData);
      }
      
      // 缩略图预加载完成后，设置响应式变量，触发一次渲染
      todayKnowledgePoints.value = processedTodayData;
      allKnowledgePoints.value = processedAllData;

      // 异步加载全部知识点的缩略图(低优先级任务)
      if (processedAllData.length > 0) {
        setTimeout(() => {
          processKnowledgePoints(processedAllData).catch(error => {
            console.error('加载全部知识点缩略图失败:', error);
          });
        }, 1000); // 延迟1秒加载，优先完成今日知识点的交互
      }

      // 更新分页并结束加载状态
      updatePagination();
      isLoading.value = false;
     
    } catch (error) {
      console.error('获取知识点数据失败:', error)
      showMessageRef.value.showMessage('获取知识点数据失败', 'error')
      isLoading.value = false
    }
  }

  async function fetchMaterials() {
    try {
      let materialsData = []
      
      try {
        const response = await axiosClient.get('/materials/');
        materialsData = response.data;
      } catch (error) {
        console.log('使用示例材料数据');
        materialsData = sampleMaterials;
      }
      
      materials.value = materialsData;
    } catch (error) {
      showMessageRef.value.showMessage('获取材料文件信息失败，使用示例数据', 'warning');
    }
  }
  
  
  watch([activeTab, itemsPerPage], () => {
    currentPage.value = 1
  })
  
  onMounted(async () => {
    // 先获取现有数据
    await fetchKnowledgePoints()
    await fetchMaterials()
    
    // 然后生成新的知识卡片
    await generateKnowledgeCards()
  })
  </script>
  
  <style scoped>
  /* 可以在这里添加额外的样式 */
  .animate-scale-in-rotate {
    animation: scaleInRotate 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
  }

  @keyframes scaleInRotate {
    0% {
      transform: scale(0) rotate(-180deg);
      opacity: 0;
    }
    100% {
      transform: scale(1) rotate(0deg);
      opacity: 1;
    }
  }
  /* 添加淡入动画 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

.animate-fadeIn {
  animation: fadeIn 0.8s ease-in-out;
  box-shadow: 0 0 15px rgba(59, 130, 246, 0.5);
  border-left: 4px solid #3b82f6;
}
</style>